<?php

declare (strict_types=1);

namespace magein\pay;

/**
 * 获取收款账号以及配置
 */
class PayAccount
{
    /**
     * 支付平台
     * @var string
     */
    protected $platform_id = '';

    /**
     * 账号索引
     * @var string
     */
    protected $account = '';

    /**
     * 账号配置
     * @var array
     */
    protected $config = [];

    /**
     * @throws PayException
     */
    public static function choose($channel_id, $platform_id = null, $account = null): PayAccount
    {
        if (is_array($channel_id)) {
            $platform_id = $channel_id['platform_id'] ?? '';
            $account = $channel_id['account'] ?? '';
            $channel_id = $channel_id['channel_id'] ?? '';
        }

        if (empty($channel_id)) {
            PayException::code(PayCode::CHANNEL_NULL);
        }

        // 获取渠道允许使用的账户
        $accounts = PayConfig::channelAccount($channel_id, $platform_id);
        if (empty($accounts)) {
            PayException::code(PayCode::CHANNEL_NULL);
        }

        if ($account) {
            if (!in_array($account, $accounts)) {
                PayException::code(PayCode::PLATFORM_ACCOUNT_NULL);
            }
        } else {
            $account = $accounts[rand(0, count($accounts) - 1)];
        }

        $self = new self();
        $self->account = $account;
        $self->platform_id = $platform_id;

        return $self;
    }

    /**
     * 获取账号索引
     * @return string
     */
    public function getAccount(): string
    {
        return $this->account;
    }

    /**
     * 获取账号配置
     * @throws PayException
     */
    public function getConfig($platform_id = null, $account = null)
    {

        $platform_id = $platform_id ?: $this->platform_id;
        $account = $account ?: $this->account;

        // 获取收款账号列表
        $platform = PayConfig::platforms($platform_id);
        // 收款账号配置
        $config = $platform['accounts'][$account] ?? '';
        if (empty($config)) {
            PayException::code(PayCode::PLATFORM_ACCOUNT_CONFIG_NULL);
        }

        return $config;
    }
}